import React from "react";
import { Modal } from "antd";
import type { ProColumns } from "@ant-design/pro-components";
import { PlusOutlined } from "@ant-design/icons";
import type { CategoryType, SearchParams } from "./types";
import { categoryApi } from "./api";
import { handleRes } from "@/utils/request";
import PcPage from "@/components/PcPage";
import usePcPage from "@/components/PcPage/hooks/usePcPage";
import useColumns from "@/components/PcTable/hooks/useColumns";
import useColumnOptions from "@/components/PcTable/hooks/useColumnOptions";
import useToolBar from "@/components/PcTable/hooks/useToolBar";
import DeleteConfirm from "@/components/DeleteConfirm";
import useDeleteConfirm from "@/components/DeleteConfirm/useDeleteConfirm";
import { message } from "antd";

// 1. 首先抽离 handleSave 函数
const handleSave = async (
  key: React.Key,
  row: CategoryType,
  pageRef: any,
  pageConfig: any
) => {
  const { id, ...data } = row;
  const isNew = id.toString().startsWith("temp_");

  try {
    await handleRes({
      api: isNew ? categoryApi.create : categoryApi.update,
      data: isNew ? data : row,
      success: {
        msg: isNew ? "创建成功" : "更新成功",
        callBack: () => {
          // 刷新列表
          pageRef.current.onSearch({
            current: pageConfig.pagination.current,
            pageSize: pageConfig.pagination.pageSize,
          });
        },
      },
    });
    return true;
  } catch (error) {
    return false;
  }
};

// 2. 抽离 handleSearch 函数
const handleSearch = async (
  values: SearchParams,
  pageConfig: any
) => {
  pageConfig.setTableLoading(true);
  try {
    const res = await handleRes({
      api: categoryApi.getList,
      data: {
        current: pageConfig.pagination.current,
        pageSize: pageConfig.pagination.pageSize,
        ...values,
      },
      returnKey: false,
    });

    pageConfig.updateDataSource(res.data.list, res.data.total);
  } finally {
    pageConfig.setTableLoading(false);
  }
};

// 3. 抽离 handleReset 函数
const handleReset = (pageRef: any, pageConfig: any) => {
  pageRef.current.onSearch({
    current: pageConfig.pagination.current,
    pageSize: pageConfig.pagination.pageSize,
  });
};

const CategoryList: React.FC = () => {
  // 创建新记录的默认值
  const createRecordTemplate = (): CategoryType => ({
    id: `temp_${Date.now()}`,
    name: "",
    sort: 0,
    status: true,
  });

  // 使用 PcPage hook，使用抽离的函数
  const { pageRef, pageConfig } = usePcPage<CategoryType, SearchParams>({
    defaultPageSize: 10,
    createRecordTemplate,
    onSave: (key, row) => handleSave(key, row, pageRef, pageConfig),
    onSearch: (values) => handleSearch(values, pageConfig),
    onReset: () => handleReset(pageRef, pageConfig),
  });

  // 使用删除确认 hook
  const { confirmProps, showConfirm, currentId } = useDeleteConfirm({
    onDelete: async () => {
      if (!currentId) return;
      await handleRes({
        api: categoryApi.delete,
        data: currentId,
        success: {
          msg: "删除成功",
          callBack: () => {
            pageRef.current.onSearch({
              current: pageConfig.pagination.current,
              pageSize: pageConfig.pagination.pageSize,
            });
          },
        },
      });
    },
    onError: () => {
      message.error("删除失败");
    },
    title: "删除分类",
    content: "确定要删除这个分类吗？删除后不可恢复。",
  });

  // 基础列配置
  const baseColumns: ProColumns<CategoryType>[] = [
    {
      title: "分类名称",
      dataIndex: "name",
      formItemProps: {
        rules: [{ required: true, message: "请输入分类名称" }],
      },
      width: "20%",
    },
    {
      title: "排序",
      dataIndex: "sort",
      valueType: "digit",
      width: "10%",
      hideInSearch: true,
    },
    {
      title: "状态",
      dataIndex: "status",
      width: 100,
      valueType: "select",
      valueEnum: {
        true: { text: "启用", status: "Success" },
        false: { text: "禁用", status: "Error" },
      },
      fieldProps: {
        options: [
          { label: "启用", value: true },
          { label: "禁用", value: false },
        ],
      },
    },
  ];

  // 使用 columns hook
  const { columns: tableColumns } = useColumns({
    columns: baseColumns,
    showIndex: true,
  });

  // 使用 columnOptions hook
  const { optionColumn } = useColumnOptions<CategoryType>({
    actions: [
      {
        text: "编辑",
        onClick: (record) => {
          pageConfig.setEditableRowKeys([record.id]);
        },
      },
      {
        text: "删除",
        type: "danger",
        onClick: (record) => showConfirm(record.id),
      },
    ],
    actionRef: pageConfig.actionRef,
  });

  // 使用 toolBar hook
  const { toolBarRender } = useToolBar({
    buttons: [
      {
        text: "新建",
        type: "primary",
        icon: <PlusOutlined />,
        onClick: () => {
          // 检查是否有正在编辑的行
          if (pageConfig?.editableKeys && pageConfig?.editableKeys.length > 0) {
            Modal.warning({
              title: "提示",
              content: "请先保存或取消当前编辑的内容",
            });
            return;
          }
          const newRecord = pageConfig.createRecordTemplate();
          // 更新数据源但不增加总数，因为还未保存
          pageConfig.updateDataSource(
            [newRecord, ...pageConfig.dataSource],
            pageConfig.pagination.total
          );
          pageConfig.setEditableRowKeys([newRecord.id]);
        },
      },
    ],
  });

  // 编辑配置
  const editConfig = {
    type: "single" as const,
    editableKeys: pageConfig?.editableKeys || [],
    actionRender: (row: CategoryType, config: any, defaultDom: any) => [
      defaultDom.save,
      defaultDom.cancel,
    ],
    onSave: async (key: React.Key, row: CategoryType) => {
      const success = await pageConfig.onSave?.(key, row);
      if (success) {
        pageConfig.setEditableRowKeys([]);
      }
    },
    onCancel: async (key: React.Key) => {
      pageConfig.onCancel(key);
      return true;
    },
  };

  return (
    <>
      <PcPage<CategoryType>
        pageRef={pageRef}
        columns={[...tableColumns, optionColumn]}
        toolBarRender={toolBarRender}
        editable={editConfig}
        {...pageConfig}
      />
      <DeleteConfirm {...confirmProps} />
    </>
  );
};

export default CategoryList;
